import statsmodels.api as sm
from gm.api import *
import talib
from tools import xiaohua_Quant_Ago as ago
from tools import Tensorflow批量单线性回归_双变量 as lr
import numpy as np
import os


def init(context):
    schedule(schedule_func=algo, date_rule='1d', time_rule='09:40:00')
    print(context.now)
    context.index = "SZSE.300296"

    context.SHORTMA = 5
    context.LONGMA = 10

def algo(context):

    now = context.now

    #这里是根据指数获取构成股票代码
    last_day = get_previous_trading_date("SZSE",now)
    data = history_n(context.index,frequency="1d",count=20,end_time=last_day,fields="open,high,low,close,volume",df=True)
    high = data["high"].values
    low = data["low"].values
    close = data["close"].values
    volume = (data["volume"].values).astype(np.double)

    MFI = talib.MFI(high, low, close, volume, timeperiod=10)
    print(MFI[-1])
    shortEMA = talib.EMA(close, context.SHORTMA)
    longEMA = talib.EMA(close, context.LONGMA)



    positions = context.account().positions()

    if len(positions) != 0 and shortEMA[-1]<longEMA[-1] and shortEMA[-2]>longEMA[-2] and MFI[-1]<40:
        order_close_all()



    elif len(positions) == 0 and shortEMA[-1]>longEMA[-1] and shortEMA[-2]<longEMA[-2] and MFI[-1]>55:
        order_target_percent(symbol=context.index, percent=1, order_type=OrderType_Market,
                             position_side=PositionSide_Long)



def on_backtest_finished(context, indicator):
    print(indicator)


if __name__ == "__main__":
    run(
        strategy_id='63e92f59-1386-11e8-bbe9-902b3463caf1',
        filename=(os.path.basename(__file__)),
        mode=MODE_BACKTEST,
        token='a71a8083b68e73817e93f7f196b030482abe5939',
        backtest_start_time='2017-01-03 09:00:00',
        backtest_end_time='2017-12-31 15:00:00',
        backtest_initial_cash=100000,
        backtest_adjust=ADJUST_PREV
    )





